<script setup lang="ts">
import { ref, onMounted } from "vue";
import RFB from "@novnc/novnc/core/rfb";

const props = defineProps<{
  port: number;
  password: string;
}>();

// 连接
let rfb: any;
const loading = ref(true);
const vncRef = ref();
const connectVnc = () => {
  const url = `ws://${window.location.hostname}:${props.port}/websockify`;
  rfb = new RFB(vncRef.value, url, {
    // 向vnc 传递的一些参数，比如说虚拟机的开机密码等
    credentials: { password: props.password, scaleViewport: true },
  });
  loading.value = false;
  rfb.scaleViewport = true; //scaleViewport指示是否应在本地扩展远程会话以使其适合其容器。禁用时，如果远程会话小于其容器，则它将居中，或者根据clipViewport它是否更大来处理。默认情况下禁用。
  rfb.resizeSession = true; //是一个boolean指示是否每当容器改变尺寸应被发送到调整远程会话的请求。默认情况下禁用
};
/**
 * 切换全屏
 */
const toggleFullscreen = () => {
  let elem = vncRef.value;
  if (!document.fullscreenElement) {
    // Launch fullscreen for browsers that support it
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    }
  } else {
    // Exit fullscreen for browsers that support it
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  }
};
defineExpose({ toggleFullscreen });

onMounted(() => {
  connectVnc();
});
</script>

<template>
  <div v-loading="loading" ref="vncRef" class="vnc" id="screen"></div>
</template>

<style lang="scss" scoped>
.vnc {
  flex: 1;
  width: 100%;
  height: 100%;
}
</style>
